<template>
  <div class="announcement-detail">
    <div class="content-wrapper">
      <el-card class="detail-card">
        <h1 class="title">{{ announcement.title }}</h1>
        <div class="meta">
          <span class="time">发布时间：{{ formatDate(announcement.createTime) }}</span>
        </div>
        <div class="content" v-html="announcement.content"></div>
      </el-card>
    </div>

    <!-- 留言区域 -->
    <el-card class="comments-card">
      <template #header>
        <div class="comments-header">
          <span>留言区</span>
          <el-button v-if="isLoggedIn" type="primary" @click="showCommentDialog">
            发表留言
          </el-button>
        </div>
      </template>

      <!-- 留言列表 -->
      <div class="comments-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <span class="username">{{ comment.username }}</span>
            <span class="time">{{ formatDate(comment.createTime) }}</span>
            <el-button
              v-if="isAdmin"
              type="danger"
              link
              @click="handleDeleteComment(comment.id)"
            >
              删除
            </el-button>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
        </div>
        <el-empty v-if="comments.length === 0" description="暂无留言" />
      </div>
    </el-card>

    <!-- 发表留言对话框 -->
    <el-dialog
      title="发表留言"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入留言内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComment" :loading="loading">
          发表
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import request from '@/utils/request'
import { formatDate, formatRelativeTime } from '@/utils'

const route = useRoute()
const userStore = useUserStore()

const announcement = ref({})
const comments = ref([])
const dialogVisible = ref(false)
const loading = ref(false)
const form = ref({ content: '' })
const rules = {
  content: [{ required: true, message: '请输入留言内容', trigger: 'blur' }]
}

const isLoggedIn = computed(() => userStore.isLoggedIn)
const isAdmin = computed(() => userStore.isAdmin)

const getAnnouncementDetail = async () => {
  try {
    const res = await request.get(`/api/announcement/${route.params.id}`)
    announcement.value = res.data
  } catch (error) {
    console.error('获取公告详情失败:', error)
  }
}

const getComments = async () => {
  try {
    const res = await request.get(`/api/announcement/${route.params.id}/comments`)
    comments.value = res.data
  } catch (error) {
    console.error('获取留言列表失败:', error)
  }
}

const showCommentDialog = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  dialogVisible.value = true
}

const submitComment = async () => {
  if (!form.value.content) {
    ElMessage.warning('请输入留言内容')
    return
  }
  
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  loading.value = true
  try {
    await request.post(`/api/announcement/${route.params.id}/comments`, null, {
      params: { content: form.value.content }
    })
    ElMessage.success('留言成功')
    dialogVisible.value = false
    form.value.content = ''
    getComments()
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.warning('请先登录')
    } else {
      console.error('留言失败:', error)
    }
  } finally {
    loading.value = false
  }
}

const handleDeleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条留言吗？', '提示', {
      type: 'warning'
    })
    await request.delete(`/api/announcement/${route.params.id}/comments/${commentId}`)
    ElMessage.success('删除成功')
    getComments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

onMounted(() => {
  getAnnouncementDetail()
  getComments()
})
</script>

<style lang="scss" scoped>
.announcement-detail {
  .content-wrapper {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
  }

  .detail-card {
    padding: 20px;

    .title {
      font-size: 24px;
      color: #303133;
      margin: 0 0 20px;
      text-align: center;
    }

    .meta {
      text-align: center;
      color: #909399;
      font-size: 14px;
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;
    }

    .content {
      line-height: 1.8;
      color: #606266;
      font-size: 16px;

      ::v-deep(img) {
        max-width: 100%;
        height: auto;
        margin: 10px 0;
      }

      ::v-deep(p) {
        margin: 16px 0;
      }
    }
  }

  .comments-card {
    .comments-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .comments-list {
      .comment-item {
        padding: 15px 0;
        border-bottom: 1px solid #ebeef5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .comment-header {
          display: flex;
          align-items: center;
          margin-bottom: 8px;
          
          .username {
            font-weight: bold;
            margin-right: 10px;
          }
          
          .time {
            color: #909399;
            font-size: 14px;
            flex: 1;
          }
        }
        
        .comment-content {
          color: #606266;
          line-height: 1.6;
        }
      }
    }
  }
}
</style> 